extends Node3D

var last_log_pos := 0
var log_label: Label
var scroll: ScrollContainer

func _ready() -> void:
	($OQ_UI2DCanvas.find_child("ReferenceRect", true, false) as Control).visible = true
	
	# we need to use find_node here since the OQ_UI2DCanvas will reparent the UI to the
	# Viewport needed to render the UI to a texture;
	log_label = $OQ_UI2DCanvas.find_child("LogLabel", true, false) as Label
	scroll = $OQ_UI2DCanvas.find_child("ScrollContainer", true, false) as ScrollContainer

func update_log() -> void:
	# this update the log by reinserting all mesages
	# !!TOOPT: can be optimized by just appending the not yet appended messages;
	#          but since the _log_buffer is a ring buffer we would need to take care of the wrap around
	log_label.text = ""
	for i in range(vr._log_buffer_count):
		var log_line := vr._log_buffer[i % vr._log_buffer.size()]
		log_label.text += log_line.message
		if (log_line.times_repeated > 1): log_label.text += " [%d]" % log_line.times_repeated
		log_label.text += "\n"
		
	var sb := scroll.get_v_scroll_bar()
	sb.value = sb.max_value # autoscroll to the last line of the log buffer

func _process(_dt: float) -> void:
	if (vr._log_buffer_index != last_log_pos):
		update_log()
		last_log_pos = vr._log_buffer_index
